from rest_framework.authentication import BaseAuthentication
from rest_framework.exceptions import AuthenticationFailed
from  user.models import Token


class UserAuth(BaseAuthentication):

    def authenticate(self, request):
        # print("认证")
        # print(request.META)
        # print(request.META.get("HTTP_TOKEN"))
        token = request.META.get("HTTP_TOKEN")
        Auth_Obj = Token.objects.filter(token=token).first()
        if not Auth_Obj:
            raise AuthenticationFailed({'code': 4000, 'error': '老师身份认证失败'})  # 认证失败，抛出失败异常

        return (Auth_Obj.user.username, Auth_Obj)  # 认证成功，返回元组